
/***
 * Measures densitometric parameters.
 * Uses sample smoothing.
 * Tamas Ungi, 2008-01-29.
 ***/
 
#include <fstream>
#include <iostream>

#include "smooth.h"
 
using namespace std;

int main ( int argc, char **argv )
{
  // process command line arguments
  if ( argc != 3 )
  {
    cout << "Usage: " << argv[ 0 ] << " inputfile outputfile" << endl;
    return 1;
  }
  char *inputfile = argv[ 1 ];
  char *outputfile = argv[ 2 ];
  
  // measurement output table will be put on std out
  cout << inputfile << " ";
  
  vector<double> sv;
  vector<double> tv;
  // read samples
  ifstream inf;
  inf.open( inputfile );
  double t;
  double v;
  while ( inf >> t ) {
    inf >> v;
    tv.push_back( t );
    sv.push_back( v );
  }
  inf.close();
  
  vector< double > otv; // original sampling points
  for ( int i = 0; i < tv.size(); ++ i )
  {
    otv.push_back ( tv[ i ] );
  }
  
  // reduce data noise
  double r_time = 0.0;
  int r_count = 0;
  while ( r_time < 1.0 )
  {
    ++ r_count;
    r_time = tv[ r_count ];
  }
  
  smooth ( tv, sv, r_count );
  
  /*
  // debug
  ofstream dst;
  dst.open ( "d.txt" );
  for ( int i = 0; i < tv.size(); ++ i )
  {
    dst << tv[ i ] << " " << sv[ i ] << endl;
  }
  dst.close();
  */
  
  // measure Gmax/Tmax on reduced curve
  double max_val = 0.0;
  int max_index = 0;
  for ( int i = 0; i < tv.size(); ++ i )
  {
    if ( sv[ i ] > max_val )
    {
      max_val = sv[ i ];
      max_index = i;
    }
  }
  double z_val = 0.0;
  int z_index = 0;
  for ( int i = max_index - 1; i >= 0; -- i )
  {
    z_val = sv[ i ];
    z_index = i;
    if ( sv[ i ] > sv[ i + 1 ] && sv[ i ] < sv[ 0 ] )
    {
      break;
    }
  }
  double gmptm = ( max_val - z_val ) / ( tv[ max_index ] - tv[ z_index ] );
  cout << gmptm << " ";
  cout << endl;
  
  // output is a line indicating Gmax/Tmax in gnuplot
  ofstream gto;
  gto.open ( outputfile );
  gto << tv[ z_index ] << " " << z_val << endl;
  gto << tv[ max_index ] << " " << max_val << endl;
  gto.close();
  
  return 0;
}
